/* 
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
/* global angular, M, wx, WeixinJSBridge */

$.browser = (function () {
    var ua = navigator.userAgent,
    tem,
    M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE';
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\bOPR\/(\d+)/);
        if (tem !== null) {
            return 'Opera';
        }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    tem = ua.match(/version\/(\d+)/i);
    if (tem !== null) {
        M.splice(1, 1, tem[1]);
    }
    return M[0];
})();
Date.prototype.format = function (fmt)
{ //author: meizz   
    var o = {
        "M+": this.getMonth() + 1, //月份   
        "d+": this.getDate(), //日   
        "h+": this.getHours(), //小时   
        "m+": this.getMinutes(), //分   
        "s+": this.getSeconds(), //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
window.TLR = {};
window.JSCopy = function (obj) {
    return JSON.parse(JSON.stringify(obj));
};
TLR.get = function () {
    var ls = $.localStorage();
    var TLR = ls.getItem("TLR");
    if (!TLR)
        TLR = {};
    ls.setItem("TLR", TLR);
    return TLR;
};
TLR.value = function (key) {
    var tlrStorage = TLR.get();
    return tlrStorage[key];
};
TLR.set = function (key, value) {
    var ls = $.localStorage();
    var TLR = ls.getItem("TLR");
    TLR[key] = value;
    ls.setItem("TLR", TLR);
};
TLR.enableLongPress = function (target, $attr, threshold) {
    var timer;
    var evt = document.createEvent('Event');
    evt.initEvent('longpress', true, true);
    target.addEventListener('touchstart', function (e) {
        e.preventDefault();
        timer = Date.now();
    }, false);
    target.addEventListener('touchend', function (e) {
        e.preventDefault();
        if (Date.now() - timer > threshold) {
            evt.duration = Date.now() - timer;
            evt.long_press_index = $attr.ngLongPressIndex;
            target.dispatchEvent(evt);
        }
    }, false);
};
TLR.event = {
    EBAN_HISTORY: 1
};
/*** MVP initialize ***/
TLR.controllers = angular.module("tlr-controllers", ['ngRoute', 'angularFileUpload']);
TLR.services = angular.module('tlr-services', ['ngResource']);
TLR.directives = angular.module("tlr-directives", []);
TLR.$ngApp = angular.module("tlr-app", ["tlr-directives", "tlr-services", "tlr-controllers"]);
var g_assessment = null;
TLR.directives.directive("ngLongPress", function () {
    return {
        restrict: 'A',
        link: function ($scope, $element, attr) {
            var callback = $scope[attr.ngLongPress];
            TLR.enableLongPress($element[0], attr, 1000);
            $element.on('longpress', callback);
        }
    };
});
TLR.$ngApp.config(function ($routeProvider) {
    $routeProvider
    .when("/building", {
        templateUrl: "app/mvp/template/view/building.html"
    });
});
TLR.scanQRCode = function (UserSrv, url, onSetQRCode) {
    UserSrv.sign({
        url: url
    }, function (res) {
        if (res.code === 0) {
            var sign = res.data;
            wx.config({
                debug: false,
                appId: sign.appId,
                timestamp: sign.timestamp,
                nonceStr: sign.nonceStr,
                signature: sign.signature,
                jsApiList: [
                    "scanQRCode"
                ]});
            wx.ready(function () {
                wx.scanQRCode({
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success: function (res) {
                        // 当needResult 为 1 时，扫码返回的结果
                        if (res.errMsg === "scanQRCode:ok") {
                            onSetQRCode(res.resultStr);
                        } else {
                            onSetQRCode("");
                            alert("扫码失败,请手工输入设备码");
                        }
                    }
                });
            });
        } else {
            alert(res.message);
        }
    });
};
TLR.getLocation = function (UserSrv, url, onLocationUpdate) {
    UserSrv.sign({
        url: url
    }, function (res) {
        if (res.code === 0) {
            var sign = res.data;
            wx.config({
                debug: false,
                appId: sign.appId,
                timestamp: sign.timestamp,
                nonceStr: sign.nonceStr,
                signature: sign.signature,
                jsApiList: [
                    "getLocation"
                ]});
            wx.ready(function () {
                wx.getLocation({
                    type: 'gcj02',
                    success: function (resLocation) {
                        if (resLocation.errMsg === "getLocation:ok") {
                            onLocationUpdate(resLocation);
                        } else {
                            alert("微信获取地理位置失败");
                        }
                    },
                    cancel: function (resLocation) {
                        alert('用户拒绝授权获取地理位置');
                    }
                });
            });
        }
    });
};

TLR.configWIFI = function (UserSrv, url) {
    UserSrv.sign({
        url: url
    }, function (res) {
        if (res.code === 0) {
            var sign = res.data;
            wx.config({
                debug: false,
                appId: sign.appId,
                timestamp: sign.timestamp,
                nonceStr: sign.nonceStr,
                signature: sign.signature,
                jsApiList: [
                    "configWXDeviceWiFi"
                ]});
            wx.ready(function () {
                WeixinJSBridge.invoke('configWXDeviceWiFi', {}, function (res) {
                    if (res.err_msg === "configWXDeviceWiFi:ok") {
                        alert("连接成功！");
                    } else {
                        alert("连接不成功！");
                    }
                });
            });
        }
    });
};

TLR.$ngApp
.constant("MAP", {
    map_min_height: 650,
    map_info_panel: 350,
    air_info_panel: 150
})
.constant("USER", {
    event: {list: 2},
    types: [{value: 1, name: "会员"}, {value: 2, name: "员工"}, {value: 3, name: "司机"}, {value: 4, name: "天樂融紧急联系员"}],
    statuses: [{value: 1, name: "激活"}, {value: 2, name: "锁定"}]
})
.constant("EMP", {
    types: [{value: 0, name: "无"}, {value: 1, name: "护工"}, {value: 2, name: "经理"}]
})
.constant("CAR", {
    event: {list: "CarList"}
})
.constant("AIR", {
    event: {list: "AirList"}
})
.constant("HEALTH", {
    event: {list: "HealthList", alert_list: "HealthAlertList"}
})
.constant("DEVICE", {
    event: {list: "DeviceList", bind_user_list: "Bind_User_List", relation_list: "Relation_List"},
    car_statuses: [{value: 1, name: "服务中"}, {value: 2, name: "等待服务"}, {value: 3, name: "停止服务"}],
    statuses: [{value: 1, name: "使用中"}, {value: 2, name: "空闲中"}, {value: 3, name: "停用"}],
    types: [{value: 1, name: "健康仪"}, {value: 2, name: "服务车"}, {value: 3, name: "空气测量仪"}, {value: 4, name: "空气净化器"}],
    status_labels: {1: "使用中", 2: "空闲中", 3: "停用"},
    type_labels: {1: "健康仪", 2: "服务车", 3: "空气测量仪", 4: "空气净化器"}
})
.run(function ($rootScope, MAP, USER, EMP, DEVICE, CAR, AIR, HEALTH) {
    $rootScope.MAP = MAP;
    $rootScope.USER = USER;
    $rootScope.EMP = EMP;
    $rootScope.DEVICE = DEVICE;
    $rootScope.CAR = CAR;
    $rootScope.AIR = AIR;
    $rootScope.HEALTH = HEALTH;
});